<template>
  <div class="app-container">
    <template v-if="!showDesignIndex">
    <div class="search-container">
      <el-form ref="form" :model="queryParams" :inline="true">
        <el-form-item prop="keywords" label="应用名称">
          <el-input
            v-model="queryParams.keywords"
            placeholder="应用名称"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery" icon="el-icon-search">搜索</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never">
      <template #header>
        <el-button type="success" @click="openDialog()"
          ><i class="el-icon-circle-plus"></i> 新增</el-button>
        <el-button
          type="danger"
          :disabled="ids.length === 0"
          @click="handleDelete()"
          ><i class="el-icon-delete"></i> 删除</el-button>
      </template>

      <el-table
        v-loading="loading"
        :data="dataList"
        highlight-current-row
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="序号" width="55" prop="dataIndex"/>
        <el-table-column label="应用名称" prop="name"/>
        <el-table-column label="应用名称（英文）" prop="enName"/>
        <el-table-column label="应用类型" prop="typeText"/>
        <el-table-column label="模板应用" prop="templateText"/>
        <el-table-column label="需微信授权" prop="wxAuthText"/>
        <el-table-column label="需二次授权" prop="reAuthText"/>
        <!-- <el-table-column label="应用状态" prop="statusText"/> -->
        <el-table-column label="更新时间" prop="updateTimeText"/>
        <el-table-column fixed="right" label="操作"  min-width="480" width="480">
          <template #default="scope">
            <el-button
              type="warning"
              size="small"
              link
              @click="openDialog(scope.row.id)"
            ><i class="el-icon-edit"></i> 编辑</el-button>
            <!-- <el-button
              type="success"
              size="small"
              link
              @click="openDialog(scope.row.id)"
            > 启用</el-button> -->
            <el-button
              type="danger"
              size="small"
              link
              @click="handleDelete(scope.row.id)"
            ><i class="el-icon-delete"></i> 删除</el-button>
            <el-button
              type="info"
              size="small"
              link
              :disabled="!scope.row.template"
              @click="copyUrl(scope.row)"
            > 复制链接</el-button>
            <el-button
              type="success"
              size="small"
              link
              :disabled="!scope.row.template"
              @click="templateDesignClick(scope.row)"
            ><i class="el-icon-edit"></i> 设计模板</el-button>
            <el-button
              type="success"
              size="small"
              link
              :disabled="!scope.row.template"
              @click="renderTemplateContent(scope.row.id)"
            ><i class="el-icon-edit"></i> 生成</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="block">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryParams.pageNum"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="10"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
    </el-card>

    <!-- 应用表单弹窗 -->
    <el-dialog
      :visible.sync="dialog.visible"
      :title="dialog.title"
      width="800px"
      :before-close="closeDialog"
      :close-on-click-modal="false"
    >
      <el-form
        ref="userFormRef"
        :model="formData"
        :rules="rules"
        label-width="240px"
      >
        <el-form-item label="应用名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入应用名称" />
        </el-form-item>
        <el-form-item label="应用名称（英文）" prop="enName">
          <el-input v-model="formData.enName" placeholder="请输入应用名称（英文）" />
        </el-form-item>
        <!-- <el-form-item label="登录成功后跳转地址" prop="redirectUrl">
          <el-input v-model="formData.redirectUrl" placeholder="请输入登录成功后跳转地址" />
        </el-form-item> -->
        <el-form-item label="应用类型" prop="type">
          <el-select v-model="formData.type" placeholder="请选择">
            <el-option label="微生态 - 公众号" value="MBIOLANCE_MINI_PROJECT_WP"></el-option>
            <el-option label="微生态 - 小程序" value="MBIOLANCE_MINI_PROJECT"></el-option>
            <el-option label="菌佑管家 - 小程序" value="MANAGE_WX_MINI"></el-option>
            <el-option label="菌佑助手 - 小程序" value="ASSISTANT_WX_MINI"></el-option>
            <el-option label="后台系统" value="MBIOLANCE_UI"></el-option>
            <el-option label="FMT - 二维码" value="QRCODE_FMT"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否模板应用" prop="template">
          <el-radio v-model="formData.template" label="false">否</el-radio>
          <el-radio v-model="formData.template" label="true">是</el-radio>
        </el-form-item>
        <el-form-item label="是否需要微信授权" prop="wxAuth" v-if="formData.template == 'true'">
          <el-radio v-model="formData.wxAuth" label="true">是</el-radio>
          <el-radio v-model="formData.wxAuth" label="false">否</el-radio>
        </el-form-item>
        <el-form-item label="是否需要二次授权（系统再次授权）" prop="reAuth" v-if="formData.template == 'true'">
          <el-radio v-model="formData.reAuth" label="true">是</el-radio>
          <el-radio v-model="formData.reAuth" label="false">否</el-radio>
        </el-form-item>
        <el-form-item label="扩展属性" prop="extJson">
          <el-input v-model="formData.extJson" type="textarea" :rows="10" placeholder="请输入扩展属性" />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="addOrUpdate">确 定</el-button>
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    </template>

    <templateDesign :checkedApp="checkedApp" v-if="showDesignIndex" @close="closeDesign"></templateDesign>

  </div>
</template>

<script>

import templateDesign from '@/views/system/application/templateDesign'
import applicationApi from '@/api/system/application'
import { formatDate } from '@/utils/formatTime'
export default {
	name: 'dictIndex',
  components: {
    templateDesign
  },
	data() {
		return {
			queryParams: {
        keywords: '',
        pageNum: 0,
        pageSize: 10,

      },
      total: 0,
      loading: false,
      dataList: [],
      ids: [],
      dialog: {},
      formData: {},
      rules: {},

      checkedApp: {},
      showDesignIndex: false,

      typeMap: {
        'MBIOLANCE_MINI_PROJECT': '微生态 - 小程序',
        'MBIOLANCE_MINI_PROJECT_WP': '微生态 - 公众号',
        'MBIOLANCE_UI': '后台系统',
        'QRCODE_FMT': 'FMT - 二维码',
        'MANAGE_WX_MINI': '菌佑管家 - 小程序',
        'ASSISTANT_WX_MINI': '菌佑助手 - 小程序'
      },
		};
	},
  methods: {
    renderTemplateContent (id) {
      applicationApi.renderTemplateContent(id).then(res => {
        this.$message({message: '应用生成成功！', type: 'success'});
      })
    },
    templateDesignClick (row) {
      this.checkedApp = row;
      this.showDesignIndex = true;
    },
    closeDesign () {
      this.showDesignIndex = false;
    },
    copyUrl (row) {
      let baseUrl = 'http://192.168.10.20:20000/platform';
      if (process.env.NODE_ENV === 'production') {
        baseUrl = process.env.VUE_APP_WX_BASE_API
      }
      this.$copyText(baseUrl + '/applications/' + row.redirectUrl);
      this.$message({message: '已复制到剪切板！', type: 'success'});
    },
    handleQuery() {
      this.loading = true;
      let params = {
        number: this.queryParams.pageNum,
        size: this.queryParams.pageSize
      };
      applicationApi.page(params).then((res) => {
        let data = res.data;
        let that = this;
        let index = 1
        data.content.forEach((v) => {
          v.createTimeText = formatDate(new Date(v.createTime), "YYYY-mm-dd HH:MM:SS")
          v.updateTimeText = formatDate(new Date(v.updateTime), "YYYY-mm-dd HH:MM:SS")
          v.typeText = this.typeMap[v.type]
          v.templateText = v.template == null ? '-' : (v.template ? '模板' : '非模板')
          v.wxAuthText = v.wxAuth == null ? '-' : (v.wxAuth ? '需要' : '不需要')
          v.reAuthText = v.reAuth == null ? '-' : (v.reAuth ? '需要' : '不需要')
          v.dataIndex = index++;
        });
        this.dataList = data.content;
        
        this.total = data.count;
        this.loading = false;
      }).catch(() => {});
    },
    resetQuery() {
      this.queryParams = {
        keywords: '',
        pageNum: 0,
        pageSize: 10,
      };
      this.handleQuery();
    },
    
    addOrUpdate() {
      let that = this;
      if (this.formData.id) {
        applicationApi.update(this.formData).then((res) => {
          this.$message({message: '应用更新成功！', type: 'success'});
          that.closeDialog();
        });
      } else {
        applicationApi.add(this.formData).then((res) => {
          this.$message({message: '应用添加成功！', type: 'success'});
          that.closeDialog();
        });
      }
    },
    openDialog(id) {
      this.$set(this.dialog, 'visible', true);
      let that = this;
      if (id) {
        this.$set(this.dialog, 'title', '编辑应用');
        applicationApi.get(id).then((res) => {
          let data = res.data;
          if (data.template != null) {
            data.template = data.template ? 'true' : 'false'
          }
          if (data.wxAuth != null) {
            data.wxAuth = data.wxAuth ? 'true' : 'false'
          }
          if (data.reAuth != null) {
            data.reAuth = data.reAuth ? 'true' : 'false'
          }
          that.formData = data;

        });
      } else {
        this.$set(this.dialog, 'title', '新增应用');
        that.formData = {};
      }

    },
    closeDialog() {
      this.$set(this.dialog, 'visible', false);
      this.$set(this.dialog, 'title', '');
      this.handleQuery();
    },
    handleDelete(id) {
      if (id) {
        applicationApi.delete(id).then((res) => {
          this.$message({message: '应用删除成功！', type: 'success'});
          this.handleQuery();
        });
      } else {
        this.$message.error('暂不支持批量删除应用！');
      }
    },
    handleSelectionChange(val) {
      this.ids = [];
      val.forEach(v => {
        this.ids.push(v.id);
      });
    },
    handleSelectionRoleChange(rows) {
      if (rows) {
        let arr = [];
        rows.forEach((v) => {
          arr.push(v.id);
        });
        this.selectRoleIdArr = arr;
      }
    },
    handleSizeChange(val) {
      this.queryParams.pageSize = val;
      this.handleQuery();
    },
    handleCurrentChange(val) {
      this.queryParams.pageNum = val;
      this.handleQuery();
    },
  },
  created() {
    this.handleQuery();
  }
};
</script>

<style scoped>
.el-pagination {
  margin-top: 10px;
  float: right;
  margin-bottom: 10px;
}
</style>